<template>
  <!--  <el-form ref="form" :model="form" label-width="80px">-->
  <el-form ref="ruleFormRef" :rules="rules" :model="form" label-width="auto"  label-position="left">
    <el-form-item label="用户昵称" prop="nickname">
      <el-input v-model="form.nickname" maxlength="30"/>
    </el-form-item>
    <el-form-item label="手机号码" prop="mobile">
      <el-input v-model="form.mobile" maxlength="11"/>
    </el-form-item>
    <el-form-item label="邮&emsp;&emsp;箱" prop="email">
      <el-input v-model="form.email" maxlength="50"/>
    </el-form-item>
    <el-form-item label="性&emsp;&emsp;别">
      <el-radio-group v-model="form.gender">
        <el-radio :value=1 label="男"></el-radio>
        <el-radio :value=2 label="女"></el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="submitForm">保存</el-button>
      <el-button type="danger" size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {defineProps, onMounted} from 'vue'
import {UserForm, UserPersonInfoForm} from "@/api/user/types";
import {ElMessage, FormRules} from "element-plus";
import {updateUserInfo} from "@/api/user";

defineOptions({
  name: "UserInfo",
  inheritAttrs: false,
});


const ruleFormRef = ref(ElForm)
const rules = reactive<FormRules<typeof ruleForm>>({
  nickname: [
    {required: false, message: 'Please input Activity name', trigger: 'blur'},
    {min: 3, max: 10, message: '长度应保持在3-10位', trigger: 'blur'},
  ],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
})
const ruleForm = reactive({
  nickname: '',
  mobile: '',
  email: '',
})


let form = reactive<UserForm>({})
const props = defineProps({
  userInfoVO: {
    type: Object,
    required: true,
  }
});

function initForm(obj: UserPersonInfoForm) {
  Object.assign(form, {...obj});
}


function submitForm() {
  console.log('submitForm!')
  ruleFormRef.value.validate((valid: any) => {
    if (valid) {
      console.log('submit!')
      updateUserInfo(form).then(() => {
        console.log('updateUserInfo success!')
        ElMessage.success('信息修改成功');
      });
    } else {
      console.log('error submit!')
    }
  });

}

function cancel() {
  console.log('cancel!')
  initForm(props.userInfoVO);

}

// 启动watch
const stopWatcher = watch(props.userInfoVO, (newValue) => {
  // 当达到某种条件时停止watch
  if (newValue) {
    console.log(props.userInfoVO)
    console.log(props.userInfoVO.username)
    initForm(props.userInfoVO);

    stopWatcher();
  }
})

onMounted(() => {
});
</script>
